import { projectIslandTimeLine, getBusinessTypeList } from '../../../../../api/index'
import { formatTimeTwo } from '../../../../../utils/util'

Component({
  properties: {
    detail: {
      type: Object,
      value: {}
    },
    roleIds: {
      type: Array,
      value: []
    }
  },
  data: {
    business: [],
    activeBusiness: '',
    businessTitle: '',
    lines: [],
    refresher: false
  },
  methods: {
    selectBusiness ({ currentTarget: { dataset: { item } } }) {
      this.selectComponent('#business').toggle()
      this.setData({ activeBusiness: item.id, businessTitle: item.title })
      this.getProgress()
    },
    async onRefresh () {
      await this.getBusiness()
      this.setData({ refresher: false })
    },
    setBusiness () {
      let business = this.data.detail.business_type.split(',')
      let newBusiness = []
      this.data.businessList.forEach(item => {
        business.forEach(row => {
          if (item.id === parseInt(row)) newBusiness.push(item)
        })
      })
      this.setData({
        business: newBusiness,
        activeBusiness: newBusiness[0].id,
        businessTitle: newBusiness[0].title
      })
    },
    async getBusiness () {
      try {
        const { ResultSet } = await getBusinessTypeList()
        this.setData({ businessList: ResultSet.userData.businessList.value })
        this.setBusiness()
        this.getProgress()
      } catch (err) {
        console.log(err)
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    },
    async getProgress () {
      try {
        const {ResultSet } = await projectIslandTimeLine({ project_id: this.data.detail.project_id, business_type: this.data.activeBusiness })
        ResultSet.userData.timeList.forEach(item => {
          item.time = formatTimeTwo(item.time * 1000, 'Y-M-D h:m:s')
          if (item.time_start) item.time_start = formatTimeTwo(item.time_start * 1000, 'Y-M-D h:m:s')
          if (item.time_end) item.time_end = formatTimeTwo(item.time_end * 1000, 'Y-M-D h:m:s')
        })
        this.setData({ lines: ResultSet.userData.timeList })
      } catch (err) {
        console.log(err)
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    }
  },
  created () {
    this.getBusiness()
  }
})